<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User\User;
use Illuminate\Support\Facades\Auth;
use Validator;


class PassportController extends Controller
{

    public $successStatus = 200;

    /**
     * login api
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function login(LoginRequest $request)
    {
        $validator = $request->validated();
        if (Auth::attempt(['username' => request('username'), 'password' => request('password'), 'is_active' => 1])) {
            $user = Auth::user();
            $success['token'] = $user->createToken('MyApp')->accessToken;
            $success['groups'] = $user->is_superuser;
            return $this->success(200, $success);
            /*$response = response()->json(['success' => $success], $this->successStatus);
            return $response;*/
        } else {
            return $this->fail(422, ['Message' => '用户名或密码错误']);
        }

    }

    /**
     * Register api
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] = $user->createToken('MyApp')->accessToken;
        $success['username'] = $user->username;
        return $this->success(200, $success);
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function getDetails()
    {
        $user = Auth::user();
        return response()->json(['message' => '登录成功', 'status_code' => $this->successStatus, 'data' => $user]);
    }

    public function logout()
    {
        $user = Auth::user();
        $user->token()->delete();
        return $this->success(200, ['data' => '登出成功！']);
    }
}
